package lzzy.com;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 线程的同步问题--多线程存钱
public class AccountWithoutSync {
    private static Account account = new Account();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        // Create and launch 100 threads
        for (int i = 0; i < 100; i++) {
            executor.execute(new AddAPennyTask());
        }

        executor.shutdown();
        // Wait until all tasks are finished
        while (!executor.isTerminated()) {
        }

        System.out.println("What is balance? " + account.getBalance());
    }
    // A thread for adding a penny to the account
    private static class AddAPennyTask implements Runnable {
        /**
         * synchronized (同步对象){
         *     线程同步代码块
         * }
         */
        public void run() {
            account.deposit(1);}
    }
    // An inner class for account
    private static class Account {
        // 显性同步锁 ReentrantLock
        private static Lock lock = new ReentrantLock();
        private int balance = 0;

        public int getBalance() {
            return balance;
        }
        // 同步关键字 synchronized
        public void deposit(int amount) {
            lock.lock();

            // This delay is deliberately added to magnify the data-corruption problem and make it easy to see
            try {
                int newBalance = balance + amount;
                Thread.sleep(5);
                balance = newBalance;
            } catch (InterruptedException ex) {
            }
            finally {
                lock.unlock();
            }
        }
    }
}